﻿namespace CP.NLayer.Client.WpfClient.Main
{
    using System;
    using System.Drawing;
    using System.IO;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Threading;
    using CP.NLayer.Client.WpfClient.Common;
    using CP.NLayer.Client.WpfClient.Login;
    using CP.NLayer.Common;
    using Microsoft.Practices.Unity;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            log4net.LogManager.GetLogger(typeof(App)).Info("Starting application...");

            // set exception handler
            Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // set UI theme
            GlobalObjects.CurrentTheme = new Telerik.Windows.Controls.MetroTheme();

            // show login view
            App.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
            var login = new LoginView();
            bool? result = null;
            try
            {
                result = login.ShowDialog();
            }
            catch (Exception)
            {
                App.Current.Shutdown();
                return;
            }

            // after login
            if (result.HasValue && result.Value == true)
            {
                App.Current.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;

                base.OnStartup(e);
                Bootstrapper bootstrapper = new Bootstrapper();
                bootstrapper.Run();
            }
            else
            {
                App.Current.Shutdown();
            }
        }

        /// <summary>
        /// Handles the exceptions thrown in current application, the app will NOT be terminated.
        /// </summary>
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            var interaction = DependencyInjection.Container.Resolve<IInteractionService>();
            var message = e.Exception.CustomMessage();
            if (string.IsNullOrEmpty(message))
            {
                log4net.LogManager.GetLogger(typeof(App)).Error("App_DispatcherUnhandledException caught", e.Exception);
                interaction.ShowError(e.Exception.Message, () => PrintScreen());
            }
            else
            {
                interaction.ShowError(message, null);
            }
            e.Handled = true;
        }

        /// <summary>
        /// Handles the exceptions which not handled by App_DispatcherUnhandledException, and the app will be terminated.
        /// </summary>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            log4net.LogManager.GetLogger(typeof(App)).Fatal("CurrentDomain_UnhandledException caught", ex);
        }

        private void PrintScreen()
        {
            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "logs", "screenshots");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";

            using (Bitmap printscreen = new Bitmap(Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth), Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight)))
            {
                using (Graphics graphics = Graphics.FromImage(printscreen as Image))
                {
                    graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
                }
                printscreen.Save(Path.Combine(path, fileName), System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }
}
